#include "Lora.h"
#include "gpio.h"
#include "stm32f0xx_usart.h"
//#include "stm32f0xx_hal_uart.h"
//#include "stm32f030xc.h"
#include "CRC16.h"

#include "stdio.h"
#include "APP_Loop.h"
#include "parameter.h"
#include "IR_Control.h"
#include "HLW8110.h"
#include "Flash_ops.h"
#include "ds1302.h"

#define HEADER_L   0xAA
#define HEADER_H   0x55


unsigned char uc_SendBuf[30];
unsigned char Uart_Loar_Recv_Buf[LORA_RECV_BUF_LENGTH];
unsigned int  ui_LocalIdleWorkMin = 0; //分钟
unsigned char uc_count = 0;
unsigned char uc_SetLoraNumFlag = 0;

UART_RcvPar str_Lora_RecvDeal;

void ReadLoraConfigInfo(void);
void ReadLoraNodeInfo(void);


static void UART_SendData(unsigned int length)
{
    unsigned int i;
		extern UART_HandleTypeDef huart3;
	
	 #ifdef RS485_EN
		HAL_UART_Transmit(&huart3, (uint8_t *)&uc_SendBuf[3], length-3,0xFFFF); //将收到的信息发送出去
		while(HAL_UART_GetState(&huart3) == HAL_UART_STATE_BUSY_TX);//检测UART发送结束
		#else
       for(i = 0; i < length; i++)
       {
						USART_SendData(USART2,uc_SendBuf[i]);
						while (USART_GetFlagStatus(USART2,USART_FLAG_TXE) == RESET);
				 
   //    	printf("%x ",uc_SendBuf[i]);
       }
		#endif
}

//E220
//M0M1 00 工作模式  11 参数配置
/*
 *Lora默认参数配置
 *
 * 9600 8N1  设备号0xff  信道 0x19
 *
 * *****/
//路由器节点配置信息
//0xc0 0x00 0x08 0x00 0x00 0x62 0x00 0x19 0x43 0x00 0x00
void Lora_InitPara(void)
{
	uc_SendBuf[0]  = 0xC0;
	uc_SendBuf[1]  = 0x00;
	uc_SendBuf[2]  = 0x06;
	uc_SendBuf[3]  = 0x00;
	uc_SendBuf[4]  = str_Device_Param.str_DeviceParam.DevNum;
	uc_SendBuf[5]  = 0x62;
	uc_SendBuf[6]  = 0x00;
	uc_SendBuf[7]  = 0x19;
	uc_SendBuf[8]  = 0x43;
	UART_SendData(9);
	HAL_Delay(50);
	ReadLoraConfigInfo();
}

void SetLoraNodeNum(void)
{
	SET_M0_H;
	SET_M1_H;
	HAL_Delay(50);
  uc_SendBuf[0]  = 0xC0;
	uc_SendBuf[1]  = 0x00;
	uc_SendBuf[2]  = 0x02;
	uc_SendBuf[3]  = 0x00;
	uc_SendBuf[4]  = str_Device_Param.str_DeviceParam.DevNum;
	UART_SendData(5);
	HAL_Delay(50);
	ReadLoraNodeInfo();
	
}

void ReadLoraNodeInfo(void)
{
int i;

		if(str_Lora_RecvDeal.UartRcvFinish_Flag == 1)
		{
			printf("ReadLoraNodeInfo\r\n");
			printf("UartRxdLen:%d\r\n",str_Lora_RecvDeal.UartRxdLen);

			for(i = 0; i < str_Lora_RecvDeal.UartRxdLen;i++)
				 printf("%x ",Uart_Loar_Recv_Buf[i]);
			
			printf("\r\n");
//			 0xc0 0x00 0x08 0x00 0x00 0x62 0x00 0x19 0x43 0x00 0x00
			if((Uart_Loar_Recv_Buf[0] == 0xc1)&&(Uart_Loar_Recv_Buf[1] == 0x00))
			{
				if(Uart_Loar_Recv_Buf[4] == str_Device_Param.str_DeviceParam.DevNum)
				{
					printf("set lora num:%d\r\n",Uart_Loar_Recv_Buf[4]);
					SET_M0_L;
					SET_M1_L;
				}
				else
				{
					uc_count++;
					if(uc_count > 10)
					{
						uc_count = 0;
						SET_M0_L;
						SET_M1_L;
						return;
					}
					printf("error %dth set lora num:%d\r\n",uc_count,Uart_Loar_Recv_Buf[4]);
					//reset
					SetLoraNodeNum();
				}
			}
			str_Lora_RecvDeal.UartRcvFinish_Flag = 0;
			str_Lora_RecvDeal.UartRxDeal_Flag = 1; //接收数据处理完成，可以接收下一帧数据
		}
}

void Lora_GPIO_Init(void)
{

  GPIO_InitTypeDef GPIO_InitStruct = {0};

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOF_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOB, GPIO_PIN_0|GPIO_PIN_1, GPIO_PIN_RESET);

  /*Configure GPIO pins : PA6 PA7 */
  GPIO_InitStruct.Pin = GPIO_PIN_0|GPIO_PIN_1;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_PULLUP;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
}



void TestLoraSendRecv(unsigned char num)
{
	SET_M0_H;
	SET_M1_H;
	uc_SendBuf[0]  = 0xC1;
	uc_SendBuf[1]  = 0x00;
	uc_SendBuf[2]  = num;
	UART_SendData(3);
//	ReadLoraConfigInfo();
}

void ReadLoraPara(void)
{
	SET_M0_H;
	SET_M1_H;

	HAL_Delay(50);
	uc_SendBuf[0]  = 0xC1;
	uc_SendBuf[1]  = 0x00;
	uc_SendBuf[2]  = 0x06;
	UART_SendData(3);
	HAL_Delay(30);
	ReadLoraConfigInfo();

	HAL_Delay(1);
//	SET_M0_L;
//	SET_M1_L;
}

void ReadLoraConfigInfo(void)
{
	int i;

		if(str_Lora_RecvDeal.UartRcvFinish_Flag == 1)
		{
			printf("ReadLoraConfigInfo\r\n");
			printf("UartRxdLen:%d\r\n",str_Lora_RecvDeal.UartRxdLen);

			for(i = 0; i < str_Lora_RecvDeal.UartRxdLen;i++)
				 printf("%x ",Uart_Loar_Recv_Buf[i]);
			
			printf("\r\n");
//			 0xc0 0x00 0x08 0x00 0x00 0x62 0x00 0x19 0x43 0x00 0x00
			if((Uart_Loar_Recv_Buf[0] == 0xc1)&&(Uart_Loar_Recv_Buf[1] == 0x00))
			{
				if((Uart_Loar_Recv_Buf[8] & 0x40) == 0)
				{
					//设置为定点传输
					printf("set para\r\n");
					uc_count++;
					if(uc_count > 50)
					{
						uc_count = 0;
						return;
					}
					Lora_InitPara();
				}
			}
			str_Lora_RecvDeal.UartRcvFinish_Flag = 0;
			str_Lora_RecvDeal.UartRxDeal_Flag = 1; //接收数据处理完成，可以接收下一帧数据
		}
}

void ReprotAdjustEvent(unsigned char EventType)
{
	const unsigned char uc_CRCLength = 5;
  unsigned char uc_CRC_Buf[uc_CRCLength];
	unsigned short ui_CRC;
	int i;
	
	uc_SendBuf[0]  = 0x00;
	uc_SendBuf[1]  = 0x00;
	uc_SendBuf[2]  = str_Device_Param.str_DeviceParam.Channel;
	
	uc_SendBuf[3]  = HEADER_L;
	uc_SendBuf[4]  = HEADER_H;
	uc_SendBuf[5]  = str_Device_Param.str_DeviceParam.DevNum;
	uc_SendBuf[6]  = EventType;
	uc_SendBuf[7]  = uc_SetParaStatus;
	
	
		for(i=0;i<uc_CRCLength;i++)
	 {
				uc_CRC_Buf[i] =  uc_SendBuf[i+3];
	 }
	ui_CRC = CRC16(uc_CRC_Buf,uc_CRCLength);

	uc_SendBuf[8]  = ui_CRC >> 8;
	uc_SendBuf[9]  = ui_CRC & 0x00ff;

	UART_SendData(10);
}

void ReprotEvent(unsigned char EventType)
{
	const unsigned char uc_CRCLength = 20;
  unsigned char uc_CRC_Buf[uc_CRCLength];
	unsigned short ui_CRC;
	int i;
	
	uc_SendBuf[0]  = 0x00;
	uc_SendBuf[1]  = 0x00;
	uc_SendBuf[2]  = str_Device_Param.str_DeviceParam.Channel;
	uc_SendBuf[3]  = HEADER_L;
	uc_SendBuf[4]  = HEADER_H;
	uc_SendBuf[5]  = str_Device_Param.str_DeviceParam.DevNum;
	uc_SendBuf[6]  = EventType;
	uc_SendBuf[7]  = !GetRelayStatus;
	uc_SendBuf[8]  = str_LocalIR_Para.fromat >> 8;
	uc_SendBuf[9]  = str_LocalIR_Para.fromat & 0xff;
	uc_SendBuf[10]  = str_LocalIR_Para.AirState;
	uc_SendBuf[11]  = str_LocalIR_Para.AirTemp;
	uc_SendBuf[12]  = temperature >> 8;
	uc_SendBuf[13]  = temperature & 0xff;
	uc_SendBuf[14]  = str_DevPowerData.DevCurrentPower >> 8;
	uc_SendBuf[15]  = str_DevPowerData.DevCurrentPower & 0xff;
	uc_SendBuf[16]  = str_DevPowerData.DevCurrentFlow >> 8;
	uc_SendBuf[17]  = str_DevPowerData.DevCurrentFlow & 0xff;
	uc_SendBuf[18]  = str_DevPowerData.DevVoltage >> 8;
	uc_SendBuf[19]  = str_DevPowerData.DevVoltage & 0xff;
	uc_SendBuf[20]  = str_DevPowerData.DevQuantityElect >> 8;
	uc_SendBuf[21]  = str_DevPowerData.DevQuantityElect & 0xff;
	uc_SendBuf[22]  = str_Device_Param.str_DeviceParam.WorkMode;

	for(i=0;i<uc_CRCLength;i++)
	 {
				uc_CRC_Buf[i] =  uc_SendBuf[i+3];
	 }
	ui_CRC = CRC16(uc_CRC_Buf,uc_CRCLength);

	uc_SendBuf[23]  = ui_CRC >> 8;
	uc_SendBuf[24]  = ui_CRC & 0x00ff;

	UART_SendData(25);
}

void HeartReport(void)
{
	//请求心跳期间，如果有事件，优先上报事件。
	//printf("HeartReport\r\n");
	if(uc_EventFlag)
		ReprotEvent(uc_EventFlag);
	else
		ReprotEvent(0x01);
}

void TemperatureCtrlEventReport(void)
{
	ReprotEvent(0x02);
}


void TimeCtrlEventReport(void)
{
	ReprotEvent(0x03);
}


void KeyEventReport(void)
{
	ReprotEvent(0x04);
}

void RemoteEventReport(void)
{
	ReprotEvent(0x05);
}

void ClockCalibrationEvent(void)
{

}

//void ClearLoraRevBuff(void)
//{
//	extern UART_HandleTypeDef huart2;
//	__HAL_UART_CLEAR_FLAG(&huart2, UART_FLAG_PE);//清标志
//	__HAL_UART_CLEAR_FLAG(&huart2, UART_FLAG_FE);
//	__HAL_UART_CLEAR_FLAG(&huart2, UART_FLAG_NE);
//	__HAL_UART_CLEAR_FLAG(&huart2, UART_FLAG_ORE);

//}

void RecvLoraData(void)
{
	int i;
	unsigned short ui_res;
	unsigned char CRC16_L,CRC16_H;

	if(str_Lora_RecvDeal.UartRcvFinish_Flag == 1)
	{
		printf("RecvLoraData\r\n");

		for(i = 0; i < str_Lora_RecvDeal.UartRxdLen;i++)
			printf("%x ",Uart_Loar_Recv_Buf[i]);

		if((Uart_Loar_Recv_Buf[0] == HEADER_L)&&(Uart_Loar_Recv_Buf[1] == HEADER_H))
		{
			ui_res = CRC16(Uart_Loar_Recv_Buf,str_Lora_RecvDeal.UartRxdLen - 2);

			CRC16_L = ui_res&0xff;
			CRC16_H = (ui_res&0xff00) >> 8;

            printf("CRC16_L = %x CRC16_H = %x\r\n",CRC16_L,CRC16_H);

//			if((CRC16_L == Uart_Loar_Recv_Buf[str_Lora_RecvDeal.UartRxdLen - 2]) && (CRC16_H == Uart_Loar_Recv_Buf[str_Lora_RecvDeal.UartRxdLen - 1]))
            if((CRC16_H == Uart_Loar_Recv_Buf[str_Lora_RecvDeal.UartRxdLen - 2]) && (CRC16_L == Uart_Loar_Recv_Buf[str_Lora_RecvDeal.UartRxdLen - 1]))
            {
				uc_EventFlag = Uart_Loar_Recv_Buf[3];
				switch(Uart_Loar_Recv_Buf[3])
					{
						case 4:
							//Adjust temp 16-30
							if(str_Device_Param.str_DeviceParam.IRUseDefCodeFlag)
								SetAirTemperatureUp();
							else
								SetAirTemperature(Uart_Loar_Recv_Buf[4]);

							break;
						case 5:
							//remote ctrl open/close
							if(Uart_Loar_Recv_Buf[4])
							{
								uc_RemoteOpenFlag = 1;
							}
							else
							{
								uc_RemoteOpenFlag = 2;
							}
							break;
						case 6:
							//remote adjust para
							switch(Uart_Loar_Recv_Buf[4])
							{
								case 1:
									//work mode
									str_Device_Param.str_DeviceParam.WorkMode = Uart_Loar_Recv_Buf[5];
									break;
								case 3:
									//IR ctrl code
									ui_RemoteAdjustIRCode = (Uart_Loar_Recv_Buf[5] << 8) | Uart_Loar_Recv_Buf[6];
									break;
								case 4:
									//temp Ctrl parameter
									str_Device_Param.str_DeviceParam.Temperature_L = Uart_Loar_Recv_Buf[5];
									str_Device_Param.str_DeviceParam.Temperature_H = Uart_Loar_Recv_Buf[6];
									break;
								case 5:
									//IR channel learn
									StartIRLearn(Uart_Loar_Recv_Buf[5]);
									uc_LearnChannel = Uart_Loar_Recv_Buf[5];
									str_Device_Param.str_DeviceParam.IRUseDefCodeFlag = 1;
									//writeFlash();
									uc_IRLearnFlag = 1;
									break;
								case 6:
									//Local Ctrl effect time
									str_Device_Param.str_DeviceParam.LocalManualWorkTime = (Uart_Loar_Recv_Buf[5] << 8) | Uart_Loar_Recv_Buf[6];
									//writeFlash();
									break;
								case 7:
									str_Device_Param.str_DeviceParam.IRUseDefCodeFlag = Uart_Loar_Recv_Buf[5];
									//writeFlash();
									break;
								case 8:
									// set Dev Num
									str_Device_Param.str_DeviceParam.DevNum = Uart_Loar_Recv_Buf[5];
									uc_SetLoraNumFlag = 1;
								//writeFlash();
								break;
							}
							writeFlash();
							break;
						case 7:
							//remote adjust timectrl para
							//str_TimeCtrl_Param.str_TimeCtrlParam.count = Uart_Loar_Recv_Buf[4];
							TimeCtrlCount = Uart_Loar_Recv_Buf[4];
							for(i=0;i<TimeCtrlCount;i++)
							{
								str_TimeCtrl_Param.uc_DevTimeParm[0][i] = Uart_Loar_Recv_Buf[5+i*4];
								str_TimeCtrl_Param.uc_DevTimeParm[1][i] = Uart_Loar_Recv_Buf[6+i*4];
								str_TimeCtrl_Param.uc_DevTimeParm[2][i] = Uart_Loar_Recv_Buf[7+i*4];
								str_TimeCtrl_Param.uc_DevTimeParm[3][i] = Uart_Loar_Recv_Buf[8+i*4];
							}
							writeFlash();
							break;
						case 8:
							//sync time
//						  if((Uart_Loar_Recv_Buf[8] != str_DevCurrentTime.str_CurrentTime.Min) || \
//							(Uart_Loar_Recv_Buf[9] != str_DevCurrentTime.str_CurrentTime.Sec))
							{
						
								for(i=0;i<8;i++)
								{
									str_DevCurrentTime.tt[i] = Uart_Loar_Recv_Buf[4+i];
								}
								//DecToHex(str_DevCurrentTime.tt);
								//if(str_DevCurrentTime.str_CurrentTime.Min)
								SyncDS1302Time(str_DevCurrentTime.tt);
							}
							break;
						case 9:
							//ReportHeart
							HeartReport();
							break;
						case 10:
							// 1 按照心跳上报 0 事件主动上报
							uc_ReportHeartEventFlag = Uart_Loar_Recv_Buf[4];
						case 11:
							// Ack上报
							uc_EventFlag = 0;
						default:
							break;

					}

			}

		}
		str_Lora_RecvDeal.UartRcvFinish_Flag = 0;
		str_Lora_RecvDeal.UartRxDeal_Flag = 1; //接收数据处理完成，可以接收下一帧数据
	}

}
